package com.greenx.hello.net.url;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

import org.apache.commons.fileupload.util.Streams;

public class CallUrlAndGetResponse {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out
				.println("\nOutput: \n"
						+ callURL("http://www.carlsonwagonlit.com/en/global/news_and_media/hot_news/rssfeed.xml"));

	}

	public static String callURL(String myURL) {
		System.out.println("Requeted URL:" + myURL);
		StringBuilder sb = new StringBuilder();
		URLConnection urlConn = null;
		InputStreamReader in = null;

		// PROXY MUST BE DELETED, ONLY USED LOCAL TESTING
		Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(
				"172.28.48.13", 3128));

		try {

			
			URL url = new URL(myURL);
			urlConn = url.openConnection(proxy);
			if (urlConn == null) {
				urlConn = url.openConnection(proxy);
			}
			if (urlConn != null)
				urlConn.setReadTimeout(60 * 1000);
			if (urlConn != null && urlConn.getInputStream() != null) {
				in = new InputStreamReader(urlConn.getInputStream(),
						Charset.defaultCharset());
				BufferedReader bufferedReader = new BufferedReader(in);
				if (bufferedReader != null) {
					int cp;
					while ((cp = bufferedReader.read()) != -1) {
						sb.append((char) cp);
					}
					bufferedReader.close();
				}
			}
			in.close();
		} catch (Exception e) {
			throw new RuntimeException("Exception while calling URL:" + myURL,
					e);
		}

		return sb.toString();
	}

}
